<template>
	<view class="container">
		<view class="go_login" v-if="token==''" @tap="go_login">
			檢測還沒登録，前往登録
		</view>

		<view class="" v-else>
			<u-tabs :list="list1" @click="click"></u-tabs>


			<view class="order_list" v-if="order_list.length">
				<scroll-view scroll-y="true" class="scroll_y" @scrolltolower="scroll">
					<view class="order_list_item" @tap="order_details(item.id)" v-for="item in order_list"
						:key="item.id">
						<view class="order_info">
							<view class="order_details">
								<view class="title">{{item.store_name}}</view>
								<view class="room">
									<view class="img">
										<u-image :src="item.room_image" :lazy-load="true"></u-image>
									</view>
									<view class="text">
										<view>{{item.room_name}}</view>
										<view>{{item.order_no}}</view>
									</view>
								</view>
								<view class="time">
									<view class="time_box">
										<view class="">{{orderStartDate(item.start)}}</view>
										<view class="">{{orderStartTime(item.start)}}</view>
									</view>
									<view class="time_box">
										<view class="">時長</view>
										<view class="">{{orderDuration(item.start)}}</view>
									</view>
									<view class="time_box">
										<view class="">{{orderEndDate(item.start)}}</view>
										<view class="">{{orderEndTime(item.start)}}</view>
									</view>
								</view>
							</view>
							<view class="order_btns">
								<view @tap.stop="paymentFns(item)"
									:style="{backgroundColor:item.status==33?'#ff914d':''}"
									:class="{active:item.status == 33}">{{orderStatusText(item.status)}}</view>
								<view v-if="item.status==33" @tap.stop="extend_time(item)">延長時間</view>
								<view @tap.stop="showPopup(item)" v-if="item.status==30">退款</view>
								<view style="background-color: #ff914d;color: #fff;border-color: #ff914d;"
									@tap.stop="openPaymentPopup(item)" v-if="item.status==10">立即付款</view>

								<view style="background-color: red;color: #fff;border-color: red;"
									@tap.stop="showDelPopup(item)" v-if="item.status==10||item.status==20">刪除</view>
							</view>
						</view>
						<view class="order_money">支付金額：<text>${{item.total_price}}</text></view>
						<view class="order_time">下單時間：{{item.time}}</view>

					</view>
					<view v-if="!flag" style="text-align: center;margin: 30rpx;">到底啦~</view>
				</scroll-view>
			</view>
			<view v-else style="margin: 30rpx;text-align: center;">暫無訂單</view>

		</view>

		<u-popup :show="show" mode="center" round="16">
			<view class="cancel">
				<view class="title">是否確定退款</view>
				<view class="cancel_btn">
					<!-- <view class="">取消</view> -->
					<!-- <view class="">確定</view> -->
					<u-button @click="show=false" text="取消"></u-button>
					<u-button @click="cancel_order" text="確定"></u-button>

				</view>
			</view>
		</u-popup>

		<u-modal :show="showDel" confirmText="確認" @confirm="confirmDel" @close="showDel=false" @cancel="showDel=false"
			:showCancelButton="true" :closeOnClickOverlay="true">
			<view class="">是否確認刪除該訂單</view>
		</u-modal>

		<u-popup :closeOnClickOverlay="true" @close="showPeymentPopup=false" :show="showPeymentPopup" round="10">
			<view class="pay_box">
				<view class="title">立即付款</view>
				<view class="money">${{orderInfo.total_price}}</view>
				<view class="pay_type">
					<u-radio-group placement="column" v-model="radioValue" @change="groupChane">
						<u-radio customStyle="margin:0 30rpx 30rpx;" labelSize="20" activeColor="#ff914d" size="20"
							iconSize="20" v-for="item in pay_type" :label="item.name" :name="item.name"></u-radio>
					</u-radio-group>
					<view v-if="radioValue=='餘額付款'" class="balance">餘額：${{userStoreInfo.balance}}</view>
				</view>

				<view class="pay_type">
					<u-button @click="confirmPay" class="custom-style" text="立即支付"></u-button>
				</view>

			</view>
		</u-popup>

		<view class="">
			<u-tabbar :value="tabbarValue" activeColor="#39B19D" :safeAreaInsetBottom="false" :placeholder="false">
				<u-tabbar-item @click="tabbarClick" v-for="(item,index) in tabber" :key="index" :text="item.text">
					<image class="u-page__item__slot-icon" slot="active-icon" :src="item.inactiveImg"></image>
					<image class="u-page__item__slot-icon" slot="inactive-icon" :src="item.activeImg"></image>
				</u-tabbar-item>
			</u-tabbar>
		</view>

	</view>
</template>

<script>
	import dayjs from "dayjs"
	import baseURL from '@/utils/baseURL.js'
	import {
		getOrderList,
		cancelOrder,
		orderDel,
		orderPay,
		getLinePayInfo
	} from '@/api/order.js'
	import {
		getUserStoreInfo
	} from '@/api/me.js'
	export default {
		data() {
			return {
				status: 0,
				// token  通過有無token判斷是否是登録狀態
				token: "",
				order_list: [],
				page: 1,
				// status: '',
				list1: [{
						name: '全部',
						status: ''
					}, {
						name: '待付款',
						status: 10
					},
					{
						name: '待使用',
						status: 30
					},
					{
						name: '進行中',
						status: 33
					},
					{
						name: '已取消',
						status: 20
					},
					{
						name: '已使用',
						status: 31
					},
					{
						name: '已過期',
						status: 32
					},
					{
						name: '待退款',
						status: 40
					},
					{
						name: '已退款',
						status: 41
					}
				],
				flag: true,
				show: false,
				cance_order: '',
				showDel: false,
				delOrder: '',
				tabber: [{
						text: '首頁',
						activeImg: '/static/images/shouyefill.png',
						inactiveImg: '/static/images/shouyefill1.png',
					},
					{
						text: '訂單',
						activeImg: '/static/images/my_order.png',
						inactiveImg: '/static/images/my_order1.png',
					},
					{
						text: '我的',
						activeImg: '/static/images/wodedamaijihuo1.png',
						inactiveImg: '/static/images/wodedamaijihuo.png',
					},
				],
				tabbarValue: 1,
				osName: '',
				tabIndex: '',
				showPeymentPopup: false,
				orderInfo: {},
				pay_type: [{
						name: '餘額付款'
					},
					// {
					// 	name: '信用卡/轉帳 藍新'
					// },
					// {
					// 	name: '信用卡/轉帳 緑界'
					// }
				],
				radioValue: '餘額付款',
				userStoreInfo: {},
				first: false,
				isLinePay: { // 判断是否唤醒linepay 支付
					flag: false,
					info: null,
				}
			};
		},
		methods: {
			setStatus: function(e) {
				// console.log(e.currentTarget.dataset.status)
				var status = e.currentTarget.dataset.status
				if (this.status != status) {
					this.status = status
				}
			},
			order_details: function(id) {
				uni.navigateTo({
					url: `/pages/order_details/order_details?id=${id}`
				})
			},
			go_login() {
				uni.navigateTo({
					url: "/pages/login_register/login_register?flag=0"
				})
			},
			click(item) {
				this.tabIndex = item.status
				getOrderList({
					page: 1,
					status: item.status
				}).then(res => {
					// console.log(res.data, '訂單列表')
					this.order_list = res.data
				})
			},
			scroll() {
				if (this.flag) {
					getOrderList({
						page: ++this.page,
						status: this.status
					}).then(res => {
						if (res.data.length) {
							this.order_list = this.order_list.concat(res.data)
						} else {
							this.flag = false
						}

					})
				}
			},
			orderStartDate(time) {
				let a = time.split('~')[0].trim().split(' ')[0]
				let b = new Date(a).getDay()
				return this.setWeek(a, b)
			},
			orderStartTime(time) {
				return time.split('~')[0].trim().split(' ')[1]
			},
			orderEndDate(time) {
				let a = time.split('~')[1].trim().split(' ')[0]
				let b = new Date(a).getDay()
				return this.setWeek(a, b)
			},
			orderEndTime(time) {
				return time.split('~')[1].trim().split(' ')[1]
			},
			setWeek(date, week) {
				switch (week) {
					case 0:
						return date + '週日';
					case 1:
						return date + '週一';
					case 2:
						return date + '週二';
					case 3:
						return date + '週三';
					case 4:
						return date + '週四';
					case 5:
						return date + '週五';
					case 6:
						return date + '週六';
				}
			},
			orderDuration(time) {
				// console.log(time,'時長')

				if (this.osName == 'ios') {
					time = time.replace(/-/g, '/')
				}

				let start = time.split('~')[0]
				let end = time.split('~')[1]
				// console.log(start, end, '111111111')
				let a = new Date(end).getTime() - new Date(start).getTime()
				let h = Math.floor(a / 60 / 60 / 1000)
				let m = Math.floor((a % (60 * 60 * 1000) / 60 / 1000))
				if (m > 0) {
					return h + '小時' + m + '分鐘'
				} else {
					return h + '小時'
				}
			},
			orderStatusText(status) {
				switch (status) {
					case 10:
						return '待付款';
					case 20:
						return '已取消';
					case 30:
						return '待使用';
					case 31:
						return '已使用';
					case 32:
						return '已過期';
					case 33:
						return '進行中';
					case 40:
						return '待退款';
					case 41:
						return '已退款';
				}
			},
			showPopup(item) {
				this.show = true
				this.cance_order = item
			},
			cancel_order() {

				cancelOrder({
					order_id: this.cance_order.id
				}).then(res => {
					if (res.code == 1) {
						uni.showToast({
							title: res.msg,
							icon: 'success',
							duration: 2000
						})
						getOrderList({
							page: 1,
							status: this.tabIndex
						}).then(res => {
							// console.log(res.data, '訂單列表')
							this.order_list = res.data
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
				this.show = false
			},
			extend_time(item) {
				this.$store.commit('updateOrderInfo', item)
				uni.navigateTo({
					// url: `/pages/order_details/extend_order/extend_order?orderInfo=${JSON.stringify(item)}`
					url: `/pages/order_details/extend_order/extend_order`
				})
			},
			showDelPopup(item) {
				this.showDel = true
				this.delOrder = item
			},
			confirmDel() {
				console.log('刪除訂單')
				orderDel({
					order_id: this.delOrder.id
				}).then(res => {
					uni.showToast({
						title: '刪除成功',
						icon: 'success'
					})
					this.showDel = false
				}).then(() => {
					getOrderList({
						page: 1,
						status: this.tabIndex
					}).then(res => {
						// console.log(res.data, '訂單列表')
						this.order_list = res.data
					})
				})
			},
			tabbarClick(e) {
				switch (e) {
					case 0:
						uni.reLaunch({
							url: '/pages/index/index'
						})
						break;
					case 2:
						if (this.token) {
							uni.reLaunch({
								url: '/pages/me/me'
							})
						} else {
							uni.navigateTo({
								url: "/pages/login_register/login_register?flag=0"
							})
						}
						break;
				}
			},
			paymentFns(item) {
				if (item.status == 10) {
					return
				}
			},
			openPaymentPopup(item) {
				this.orderInfo = item
				this.showPeymentPopup = true
				this.getUserStoreInfoFn()
			},
			getUserStoreInfoFn() {
				getUserStoreInfo({
					store_id: this.orderInfo.store_id
				}).then(res => {
					this.userStoreInfo = res.data
					this.setPayment(res.data.pay_type_list)
				})
			},
			setPayment(arr) {
				if (this.first) return
				this.first = true
				arr.forEach(item => {
					switch (item) {
						case 1:
							this.pay_type.push({
								name: '信用卡/轉帳 藍新',
								checked: false
							})
							if (this.systemInfo.platform == 'ios' && this.orderInfo.store_id == 76) {
								this.pay_type.push({
									name: 'Apple pay',
									checked: false
								})
							}
							break;
						case 2:
							this.pay_type.push({
								name: '信用卡/轉帳 綠界',
								checked: false
							})
							break;
						case 4:
							if (this.orderInfo.store_id == 76) {
								this.pay_type.push({
									name: 'Line Pay',
									checked: false
								})
							}

							break;
						case 9:
							if (this.orderInfo.store_id == 76) {
								this.pay_type.push({
									name: 'Apple pay',
									checked: false
								})
							}

							break;
						case 10:
							if (this.systemInfo.platform == 'Android') {
								this.pay_type.push({
									name: 'Google pay',
									checked: false
								})
							}
							break;
					}
				})
			},
			groupChane(e) {
				// console.log(e)
				this.radioValue = e
			},
			confirmPay() {
				// console.log(this.orderInfo)
				let pay_type = ''
				switch (this.radioValue) {
					case '信用卡/轉帳 藍新':
						pay_type = 1
						break;
					case '信用卡/轉帳 緑界':
						pay_type = 2
						break;
					case '超商付款':
						pay_type = 3
						break;
					case 'Line Pay':
						pay_type = 4
						break;
					case '儲值機':
						pay_type = 5
						break;
					case '餘額付款':
						pay_type = 6
						break;
					case '儲值卡':
						pay_type = 7
						break;
					case '電子票券':
						pay_type = 8
						break;
					case 'Apple Pay':
						pay_type = 9
						break;
				}
				this.paymentFn(pay_type)
			},
			paymentFn(pay_type) {
				const params = {
					order_id: this.orderInfo.id,
					pay_type
				}
				if (pay_type == 6) {
					if (this.orderInfo.total_price > this.userStoreInfo.balance) {
						uni.showToast({
							title: '餘額不足',
							icon: 'none'
						})
						return
					}
				}

				orderPay(params).then(res => {
					this.paymentResult(res, pay_type)
				})
			},
			paymentResult(res, pay_type) {
				if (res.code !== 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					uni.setStorageSync('MerchantTradeNo', res.data.MerchantTradeNo)
					this.showPeymentPopup = false
					switch (pay_type) {
						case 1:
							uni.navigateTo({
								url: `/pages/book_now/outward_payment/outward_payment?payData=${JSON.stringify(res.data)}&type=1`
							})
							break;
						case 2:
							uni.navigateTo({
								url: `/pages/book_now/outward_payment/outward_payment?form=${JSON.stringify(res.data)}&type=2`
							})
							break;
						case 6:
							uni.showToast({
								title: '付款成功',
								icon: 'success'
							})
							getOrderList({
								page: 1,
								status: this.tabIndex
							}).then(res => {
								// console.log(res.data, '訂單列表')
								this.order_list = res.data
							})
							break;
						case 4:
							this.wakeUp(res.data.result)
							this.isLinePay = {
								flag: true,
								info: res.data.pay_log
							}
							break;
						case 9:
							uni.navigateTo({
								url: `/pages/book_now/outward_payment/outward_payment?AppleForm=${JSON.stringify(res.data)}&type=9`
							})
							break;
					}
				}
			},
			wakeUp(path) {
				const systemInfo = uni.getSystemInfoSync()
				// #ifdef APP-PLUS
				if (systemInfo.platform === 'Android') {
					const params = {
						pname: 'jp.naver.line.android',
						action: 'line://'
					}
					if (this.determine(params)) {
						// 已下載line pay
						plus.runtime.openURL(path, function() {
							// plus.nativeUI.alert('本機未安裝指定的應用')
						})
					} else {
						plus.runtime.openURL(`market://details?id=${params.pname}`, function() {
							// plus.nativeUI.alert('本機未安裝指定的應用')
						})
					}
				} else if (systemInfo.platform === 'ios') {
					const params = {
						appid: ''
					}
					plus.runtime.launchApplication({
						action: path
					}, function() {
						plus.nativeUI.actionSheet({
							title: '應用市場',
							cancel: '取消',
							buttons: [{
								title: '應用市場'
							}]
						}, function({
							index
						}) {
							switch (index) {
								case 1:
									plus.runtime.openURL(
										`itms-apps://itunes.apple.com`,
										function() {
											// plus.nativeUI.alert('本機未安裝指定的應用')
										})
							}
						})
					})
					// this.determine()
					plus.runtime.openURL(path, function() {
						// plus.nativeUI.alert('本機未安裝指定的應用')
					})
				}
				// #endif

				// #ifdef H5
				// uni.navigateTo({
				// 	url: `/pages/book_now/outward_payment/outward_payment?url=${path}&type=4`
				// })

				const userAgent = navigator.userAgent
				if (/(Android)/i.test(userAgent)) {
					// Android平台
					window.location.href = path
				} else if (/iPhone|iPad|iPod/i.test(userAgent)) {
					// ios平台
					window.location.href = path
				}

				// #endif

			},
			determine() {
				const install = plus.runtime.isApplicationExist()
				return install
			},
			linePayFn() {
				if (this.isLinePay.flag && this.isLinePay.info) {
					uni.showLoading({
						title: '加载中...'
					})
					setTimeout(() => {
						getLinePayInfo({
							...this.isLinePay.info
						}).then(res => {
							console.log(res)
							if (res.code == 1) {
								uni.showToast({
									title: res.msg,
									icon: 'success',
									duration: 6000
								})
								setTimeout(() => {
									uni.reLaunch({
										url: `/pages/order_details/order_details?id=${res.data.id}`
									})
								}, 1500)
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 6000
								})
							}
						})
					}, 1000)
				}
			},
		},
		onShow() {
			// 獲取token
			this.token = uni.getStorageSync('ONEtoken')
			// console.log(this.token, "token")

			if (this.token == '') {
				uni.navigateTo({
					url: "/pages/login_register/login_register?flag=0"
				})
			} else {
				// 獲取當前賬戶訂單
				getOrderList({
					page: 1,
					status: this.tabIndex
				}).then(res => {
					console.log(res.data, '訂單列表')
					this.order_list = res.data
				})
			}

			uni.getSystemInfo({
				success: (res) => {
					// console.log(res.osName,'系統信息')
					this.osName = res.osName
				}
			})
			this.linePayFn()

			// this.orderDuration('2023-08-19 16:19 ~ 2023-08-19 18:19')

		}
	}
</script>

<style lang="less">
	.container {
		padding: 15rpx 30rpx;
		box-sizing: border-box;
		height: calc(100vh - 175rpx);
		background: #F3F5F9;

		.nav {
			padding: 0 37rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;

			.nav_list {
				font-size: 28rpx;
				color: #000;
				font-weight: 400;
			}

			.active {
				position: relative;
				font-weight: bold;

				&::after {
					content: "";
					display: block;
					position: absolute;
					left: 0%;
					bottom: 0%;
					width: 100%;
					height: 10rpx;
					background: #39B19D;
					border-radius: 5rpx 5rpx 5rpx 5rpx;
					opacity: 0.7;
					margin-top: 5rpx;
				}
			}
		}

		.order_list {
			margin-top: 31rpx;

			.order_list_item {
				width: 100%;
				min-height: 382rpx;
				background: #fff;
				border-radius: 16rpx;
				padding: 15rpx 34rpx 15rpx 23rpx;
				box-sizing: border-box;
				margin-bottom: 31rpx;

				.order_info {
					display: flex;
					justify-content: space-between;
					margin-bottom: 23rpx;

					.order_details {
						.title {
							font-size: 36rpx;
							font-weight: bold;
							color: #000;
							margin-bottom: 11rpx;
						}

						.room {
							display: flex;
							margin-bottom: 22rpx;

							.img {
								width: 126rpx;
								height: 113rpx;
								border-radius: 16rpx;
								// background: skyblue;
								margin-right: 22rpx;

								/deep/ .u-image__image {
									width: 126rpx !important;
									height: 113rpx !important;
									border-radius: 16rpx !important;
								}

								/deep/ .u-image__error {
									width: 126rpx !important;
									height: 113rpx !important;
									border-radius: 16rpx !important;
								}

								/deep/ .u-image__loading {
									width: 126rpx !important;
									height: 113rpx !important;
									border-radius: 16rpx !important;
								}
							}

							.text {
								view {
									margin-top: 11rpx;
									font-size: 30rpx;
									font-weight: 400;
									color: #000;

								}
							}
						}

						.time {
							display: flex;

							.time_box {
								text-align: center;

								&:nth-child(2) {
									margin: 0 30rpx;
								}

								view {
									color: #999;
									font-size: 26rpx;

									&:last-child {
										font-size: 30rpx;
										color: #000;
									}
								}
							}
						}
					}

					.order_btns {
						margin-top: 20rpx;

						view {
							width: 127rpx;
							height: 48rpx;
							background: #fff;
							border-radius: 16rpx 16rpx 16rpx 16rpx;
							opacity: 1;
							border: 1rpx solid #39B19D;
							color: #39B19D;
							text-align: center;
							line-height: 48rpx;
							font-size: 30rpx;
							margin-bottom: 20rpx;
							// background-color: #39B19D;

							&:first-child {
								background-color: #39B19D;
								color: #fff;
							}
						}

						.active {
							background-color: #ff914d;
							border-color: #ff914d;
						}
					}
				}

				.order_money,
				.order_time {
					font-size: 30rpx;
					font-weight: 400;
					margin-bottom: 6rpx;

					text {
						color: #FA533D;
					}
				}
			}
		}

		.mask {
			// background: white;
			text-align: center;
		}

		.go_login {
			padding: 10rpx 30rpx;
			// display: inline-block;
			margin: 30rpx auto;
			text-align: center;
			background: #39B19D;
			border-radius: 16rpx;
			color: white;
		}

		.scroll_y {
			height: 80vh;
			// background-color: skyblue;
		}

		.cancel {
			width: 690rpx;
			height: 200rpx;
			padding: 30rpx;
			box-sizing: border-box;
			font-size: 32rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.title {
				margin-bottom: 30rpx;
				text-align: center;
			}

			.cancel_btn {
				display: flex;
			}
		}
	}

	.u-page__item__slot-icon {
		width: 50rpx;
		height: 50rpx;
	}

	/deep/ .u-tabbar__content__item-wrapper {
		height: 120rpx !important;
	}

	.pay_box {
		height: 60vh;
		padding: 30rpx;
		box-sizing: border-box;

		.title {
			font-size: 32rpx;
			text-align: center;
			margin-bottom: 40rpx;
		}

		.money {
			color: #ff914d;
			font-weight: 600;
			font-size: 48rpx;
			text-align: center;
			margin-bottom: 60rpx;
		}

		.pay_type {
			margin-top: 100rpx;
			position: relative;

			.balance {
				position: absolute;
				top: 0rpx;
				right: 0%;
				font-size: 30rpx;
				color: #ff914d;
			}

			.custom-style {
				background-color: #39B19D;
				color: #fff;
				width: 500rpx;
			}
		}

	}
</style>